package com.ys.service.wallet.eth.erc20;

import cn.hutool.json.JSONUtil;
import com.ys.entity.WalletWithdraw;
import com.ys.service.wallet.eth.EthWalletServiceBase;
import com.ys.util.EthUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthSendTransaction;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;


/**
 * erc20 钱包转账
 */
@Component
@Slf4j
@Data
public class Erc20WalletService extends EthWalletServiceBase {

    @Autowired
    public Web3j web3j;

    /**
     * 发送提币交易
     * @param walletWithdraw
     * @return
     */
    public String sendWithDraw(WalletWithdraw walletWithdraw) {
        String transactionID ;
        try {
            BigDecimal gd = new BigDecimal(String.valueOf(walletWithdraw.getWithdrawAmount()));
            BigDecimal decimals = new BigDecimal(currencyEnum().decimal);
            BigDecimal v = gd.multiply(decimals);
            Function function = new Function(
                    "transfer",  // function we're calling
                    Arrays.asList(new Address(walletWithdraw.getToAddress()), new Uint256(v.toBigInteger())),
                    // Parameters to pass as Solidity Types
                    Collections.emptyList());
            String encodedFunction = FunctionEncoder.encode(function);
            //gas
            BigInteger gas = BigInteger.valueOf(420000L);
            String contractAddress=currencyEnum().contractAddress;
            Transaction transaction = Transaction.createFunctionCallTransaction(
                    getWithDrawAddress(), null, EthUtil.hexToBigInteger(gasPrice()),
                    gas,
                    contractAddress, new BigInteger("0"), encodedFunction);
            /** 解锁账号 **/
            unlock(getWithDrawAddress(),getWithDrawAddressPwd());
            log.info("erc20提币参数："+JSONUtil.toJsonStr(transaction)+",提币任务ｗalletdraw="+JSONUtil.toJsonStr(walletWithdraw));
            EthSendTransaction transactionResponse = web3j.ethSendTransaction(transaction).send();
            log.info("erc20提币结果："+JSONUtil.toJsonStr(transactionResponse)+",提币任务ｗalletdraw="+JSONUtil.toJsonStr(walletWithdraw));
            transactionID = transactionResponse.getTransactionHash();
            return transactionID;
        }
        catch (Throwable e){
            e.printStackTrace();
            log.info("erc20提币失败　withdraw="+ JSONUtil.toJsonStr(walletWithdraw),e);
        }finally {
            lock(getWithDrawAddress());
        }
        return null;

    }
}
